import random
import re
from datetime import datetime

from flask import abort
from flask import current_app
from flask import g
from flask import make_response
from flask import render_template, jsonify
from flask import request
from flask import session

from info import constants, db
from info import redis_store
from info.models import User
from info.modules.passport import passport_blu
from info.utils.captcha.captcha import captcha
from info.utils.common import user_login
from info.utils.response_code import RET


@passport_blu.route("/user", methods=["POST"])
@user_login
def user():
    user = g.user

    dict_data = request.json

    mobile = dict_data.get("mobile")
    phonecode = dict_data.get("phonecode")
    password = dict_data.get("password")

    if not all([mobile, phonecode, password]):
        return jsonify(errno= RET.PARAMERR ,errmsg= "参数错误")

    if not re.match(r"1[35678]\d{9}", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式不正确")

    try:
        real_sms_code = redis_store.get("SMS" + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    if not real_sms_code:
        return jsonify(errno=RET.NODATA, errmsg="短信验证码过时")
    if real_sms_code != phonecode:
        return jsonify(errno=RET.DATAERR, errmsg="手机验证码错误")

    user = User()

    user.name = mobile
    # user.password_hash = generate_password_hash(password)
    user.password_hash = password
    user.mobile = mobile

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR , errmsg= "数据库保存失败")

    session["user_id"] = user.id
    return jsonify(errno=RET.OK, errmsg="ok")


@passport_blu.route("/smscode", methods=["post"])
@user_login
def smscode():
    dict_data = request.json

    mobile = dict_data.get("mobile")
    image_code = dict_data.get("image_code")
    image_code_id = dict_data.get("image_code_id")


    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno= RET.PARAMERR ,errmsg= "参数错误")

    if not re.match(r"^1[35678]\d{9}$", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式不正确")

    try:
        real_image_code = redis_store.get("imageCodeID" + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg="验证码无数据")

    if image_code.upper() != real_image_code.upper():
        return jsonify(errno=RET.DATAERR, errmsg="验证码数据错误")

    sms_code_str = "%06d" % random.randint(0, 999999)
    current_app.logger.info("手机验证码:%s" % sms_code_str)
    # result = CCP().send_template_sms(mobile, [sms_code_str, 5], 1)
    #
    # if result != 0:
    #     return jsonify(errno= RET.THIRDERR, errmsg= "第三方系统错误")
    try:
        redis_store.setex("SMS" + mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code_str)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    return jsonify(errno=RET.OK, errmsg="手机验证码成功")


@passport_blu.route("/imagecode")
def get_imagecode():
    image_code_id = request.args.get("cur", None)
    if not image_code_id:
        abort(404)

    _, text, image = captcha.generate_captcha()
    current_app.logger.info("图片验证码为:%s" % text)

    try:
        redis_store.setex("imageCodeID"+ image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
    except Exception as e:
        current_app.logger.error(e)
        abort(500)

    response = make_response(image)
    response.headers["Content-Type"] = "image/jpg"

    return response


# @passport_blu.route("/seeion",  methods=["post"])
# @user_login
# def seeion():
#
#     return render_template("register.html")
# @passport_blu.route("/session",  methods=["post"])
# @user_login
# def session():
#     dict_data = request.json
#     mobile = dict_data.get("mobile")
#     passport = dict_data.get("passport")
#
#     if not all([mobile, passport]):
#         return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
#
#     if not re.match(r"1[35678]\d{9}", mobile):
#         return jsonify(errno=RET.PARAMERR, errmsg="手机号的格式不正确")
#
#     try:
#         user = User.query.filter_by(mobile=mobile).first()
#     except Exception as e:
#         current_app.logger.error(e)
#         return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
#
#     if not user:
#         return jsonify(errno=RET.NODATA, errmsg="用户没有注册")
#
#     if not user.check_passowrd(passport):
#         return jsonify(errno=RET.DATAERR, errmsg="密码输入错误")
#
#     user.last_login = datetime.now()
#
#     try:
#         db.session.commit()
#     except Exception as e:
#         db.session.rollback()
#         current_app.logger.error(e)
#         return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
#
#     session["user_id"] = user.id
#
#     return jsonify(errno=RET.OK, errmsg="登录成功")
#
